package com.demo.controller;

import com.demo.entity.Employee;
import com.demo.util.ResultEntity;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.ribbon.proxy.annotation.Hystrix;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;


/**
 * @author Stone
 * @date 2020/6/15 15:47
 */
@RestController
public class EmployeeController {

    /**
     * @Author:Stone
       * @Param request:
       * @return: com.demo.entity.Employee
     * @Date: 2020/6/16 18:56
     * @Description: 使用RestTemplate远程访问服务
    */
//    @RequestMapping("/provider/get/employee/remote")
//    public Employee getEmployeeRemote(HttpServletRequest request) {
//        int serverPort = request.getServerPort();
//        return new Employee(555, "tom555"+serverPort, 555.55);
//    }

    /**
     * @Author:Stone

       * @return: com.demo.entity.Employee
     * @Date: 2020/6/16 18:56
     * @Description: 使用Feign实现远程调度
    */
    @RequestMapping("/provider/get/employee/remote")
    public Employee getEmployeeRemote(){
        return new Employee(555, "tom555", 555.55);
    }

    /**
     * @Author:Stone
       * @Param keyword:
       * @return: com.demo.util.ResultEntity<com.demo.entity.Employee>
     * @Date: 2020/6/18 12:14
     * @Description: HystrixCommand 发生异常的时候，指定另一个返回类型，参数一模一样的方法。
     *               启动Hystrix的熔断机制
    */
    @HystrixCommand(fallbackMethod = "getEmpBackup")
    @RequestMapping("/provider/circuit/get/employee")
    public ResultEntity<Employee> getEmp(@RequestParam("keyword") String keyword) throws InterruptedException {
        if("shortBang".equals(keyword)){
            throw new RuntimeException();
        }

        if("longBang".equals(keyword)){
            Thread.sleep(5000);
        }
        return ResultEntity.successWithData(new Employee(66,"666",666.66));
    }

    /**
     * @Author:Stone
       * @Param keyword:
       * @return: com.demo.util.ResultEntity<com.demo.entity.Employee>
     * @Date: 2020/6/18 14:57
     * @Description:熔断机制时，调用的备用方法
    */
    public ResultEntity<Employee> getEmpBackup(@RequestParam String keyword) throws InterruptedException {
        return ResultEntity.successWithData(new Employee(55,"555",555.55));
    }


}
